const db = wx.cloud.database()
const mybook_db = db.collection('mybook')
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    movie_positon: {
      x: 300,
      y: 400
    },
    mybooks: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    mybook_db.get({
      success: res => {
        console.log("onLoad", res.data)
        // let bookItem = res.data[0]
        // let arr = []
        // for (let i = 0; i < 10; i++) {
        //   arr.push(bookItem)
        // }
        this.setData({
          mybooks: res.data
        })
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    mybook_db.get({
      success: res => {
        this.setData({
          mybooks: res.data
        })
        wx.stopPullDownRefresh();
      }
    })
  },
  onShareAppMessage() {

  },
  //查看详情
  viewItem: function (event) {
    var id = event.currentTarget.dataset.id
    wx.navigateTo({
      url: "bookDetail/bookDetail?id=" + id,
    })
  },

  //删除书籍
  deleteBook: function (event) {
    var _this = this;
    var book_id = event.currentTarget.dataset.id
    var book_name = event.currentTarget.dataset.name
    console.log('删除书籍', book_id, book_name)
    mybook_db.doc(book_id).remove({
      success: function (res) {
        console.log(res)
        wx.showToast({
          icon: 'none',
          title: '删除《' + book_name + '》成功！'
        })
        var mybooks_new = _this.data.mybooks
        for (var i = 0; i < mybooks_new.length; i++) {
          if (mybooks_new[i]._id === book_id) {
            mybooks_new.splice(i, 1);
          }
        }
        console.log(mybooks_new)
        _this.setData({
          mybooks: mybooks_new
        })
      }
    })
  },

  //扫码二维码
  scanCode: function (event) {
    // 允许从相机和相册扫码
    var _this = this
    wx.scanCode({
      scanType: ['barCode'],
      success(res) {
        _this.getBookInfo(res);
      },
      fail(err) {
        console.log("二维码获取错误" + err)
      }
    })
  },

  // 扫码成功，调用云函数查询书籍的信息
  getBookInfo: function (res) {
    var _this = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.callFunction({
      name: 'bookinfo',
      data: {
        isbn: res.result
      },
      success: function (res) {
        var bookStr = res.result;
        //接口返回的书籍对象
        var bookOjb = JSON.parse(bookStr);
        _this.saveBookInfo(bookOjb)
      },
      fail: console.error
    })
  },

  //保存图书逻辑
  saveBookInfo: function (bookOjb) {
    //判断书籍是否存在
    var is_book_in = false
    this.data.mybooks.forEach(bookInfo => {
      if (bookInfo.isbn13 === bookOjb.isbn13) {
        is_book_in = true
      }
    });
    wx.hideLoading();
    //如果不存在保存图书
    if (is_book_in === false) {
      // 保存到数据库
      mybook_db.add({
          data: bookOjb
        })
        .then(res => {
          console.log(res)
          wx.showToast({
            icon: 'none',
            title: '添加《' + bookOjb.title + '》成功！'
          })
          bookOjb._id = res._id;
          var mybooks_new = this.data.mybooks
          mybooks_new.push(bookOjb)
          console.log(mybooks_new)
          this.setData({
            mybooks: mybooks_new
          })
        }).catch(err => {
          console.log(err)
        })
    } else {
      Dialog.alert({
        message: "《" + bookOjb.title + "》" + "已经存在！"
      }).then(() => {
        // on close
      });
    }
  }
})